package utils

import (
	"fmt"
	"math/rand"
	"slices"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

func StringToInt(str string) int {
	i, _ := strconv.Atoi(str)
	return i
}

func StringToUint(str string) uint {
	i, _ := strconv.ParseUint(str, 10, 64)
	return uint(i)
}

func StringToInt64(str string) int64 {
	i, _ := strconv.ParseInt(str, 10, 64)
	return i
}

func Float64ToFloat64(str string, num float64) float64 {
	result := fmt.Sprintf(str, num)
	num, _ = strconv.ParseFloat(result, 64)
	return num
}

func Float64ToString(f float64) string {
	return fmt.Sprintf("%.2f", f)
}

func Float64sToString(floats []float64) string {
	strs := make([]string, len(floats))
	for i, f := range floats {
		strs[i] = fmt.Sprintf("%.2f", f)
	}
	return strings.Join(strs, ",")
}

func StringToFloat64(str string) float64 {
	num, _ := strconv.ParseFloat(str, 64)
	return num
}

func IntToString(i int) string {
	return strconv.Itoa(i)
}

func UintToString(i uint) string {
	return strconv.Itoa(int(i))
}

func Int64ToString(i int64) string {
	return strconv.FormatInt(i, 10)
}

func Uint64ToString(i uint64) string {
	return strconv.FormatUint(i, 10)
}

func RandStr(n int) string {
	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}

// Substring 截取字符串，支持多字节字符（如汉字）
func Substr(s string, length int) string {
	if length <= 0 {
		return ""
	}

	var result strings.Builder
	var count int

	for i := 0; i < len(s); {
		r, size := utf8.DecodeRuneInString(s[i:])
		if r == utf8.RuneError && size == 1 {
			break
		}
		result.WriteRune(r)
		i += size
		count++

		if count >= length {
			break
		}
	}

	return result.String()
}

func GenerateOrderID() string {
	// Get the current time
	now := time.Now()

	// Format the date and time part
	datePart := now.Format("20060102150405") // YYYYMMDDHHMMSS

	// Create a local random number generator
	r := rand.New(rand.NewSource(now.UnixNano()))

	// Generate the random part (4 digits)
	randomPart := fmt.Sprintf("%04d", r.Intn(10000))

	// Combine into an order ID
	orderID := datePart + randomPart
	return orderID
}

// IsElementInSlice 判断元素是否在切片中
func IsElementInSlice(slice []int, target int) bool {
	return slices.Contains(slice, target)
}

// 生成随机数字
func GenerateRandomNumber(length int) string {
	min := int64(1)
	max := int64(9)
	for range length - 1 {
		min *= 10
		max *= 10
	}
	randomNumber := rand.Int63n(max-min+1) + min
	return strconv.FormatInt(randomNumber, 10)
}

func SubstrReplace(str string, replacement string, start int, length int) string {
	if str == "" {
		return str
	}
	if start < 0 {
		start = max(len(str)+start, 0)
	}
	if start > len(str) {
		start = len(str)
	}
	if length < 0 {
		length = max(len(str)+length-start, 0)
	}
	if start+length > len(str) {
		length = len(str) - start
	}
	return str[:start] + replacement + str[start+length:]
}

func SubstrInt(i int) string {
	str := strconv.Itoa(i)
	if len(str) >= 2 {
		return str[:2]
	} else {
		return str
	}
}

func SpliteStringToInt64(str string) []int64 {
	parts := strings.Split(str, ",")
	result := make([]int64, 0, len(parts))
	for _, part := range parts {
		num, err := strconv.ParseInt(strings.TrimSpace(part), 10, 64)
		if err == nil {
			result = append(result, num)
		}
	}
	return result
}
